package saucaca.fragment;

import java.util.ArrayList;

import org.json.JSONException;

import saucaca.Adapter.CommentAdapter;
import saucaca.CustomView.ProgressBarCircularIndeterminate;
import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.AlbumObject;
import saucaca.Object.CommentObject;
import saucaca.Object.HomeData;
import saucaca.Object.SongObject;
import saucaca.Util.PreferenceUtils;
import saucaca.Util.TagName;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.lemon.kenhnhacvn.BaseEngine;
import com.lemon.kenhnhacvn.R;

public class CommentFragment extends Fragment implements OnScrollListener {
	Context context;
	ImageLoader imageLoader;
	private ListView listViewComnent;
	ImageView imgSend;
	EditText edtText;
	TextView txtStatus;
	String page = "0";
	String pageSize = "";
	int xpage = 0;
	boolean loadingMore;
	SongObject songObject;
	AlbumObject albumObject;
	String audioID = null;
	String type_SongAlbum;
	ArrayList<CommentObject> listComment;
	CommentAdapter adapter;
	AlertDialog alertDialog;
	RelativeLayout layout_comment;
	View empty_loading;
	ProgressBar empty_progress;
	ImageView empty_error, empty_noitem;
	TextView empty_text;
	float lastX;

	ProgressBarCircularIndeterminate progressBarFooter;
	int m_PreviousTotalCount = 0;

	public static CommentFragment newInstance(SongObject id, String type_SongAlbum) {
		CommentFragment f = new CommentFragment();
		Bundle args = new Bundle();
		args.putSerializable(TagName.object, id);
		args.putString(TagName.stringkey, type_SongAlbum);
		f.setArguments(args);
		return f;
	}

	public void update(SongObject id, String type_SongAlbum) {
		this.songObject = id;
		this.type_SongAlbum = type_SongAlbum;
		audioID = songObject.getSONG_ID();
		if (songObject.getFormNet())
			new listCommentService().execute(audioID);
		showView(songObject.getFormNet());
	}

	public static CommentFragment newInstance(AlbumObject id, String type_SongAlbum) {
		CommentFragment f = new CommentFragment();
		Bundle args = new Bundle();
		args.putSerializable(TagName.object, id);
		args.putString(TagName.stringkey, type_SongAlbum);
		f.setArguments(args);
		return f;
	}

	public void update(AlbumObject album, String type_SongAlbum) {
		this.type_SongAlbum = type_SongAlbum;
		audioID = album.getALBUM_ID();
		this.albumObject = album;
		new listCommentService().execute(audioID);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View android = inflater.inflate(R.layout.comment, container, false);
		context = getActivity();
		findviewByID(android);
		
		if (getArguments() != null) {
			Bundle b = getArguments();
			try {
				songObject = (SongObject) b.getSerializable(TagName.object);
				this.type_SongAlbum = b.getString(TagName.stringkey);
				audioID = songObject.getSONG_ID();
			} catch (Exception e) {
				try {
					albumObject = (AlbumObject) b.getSerializable(TagName.object);
					this.type_SongAlbum = b.getString(TagName.stringkey);
					audioID = albumObject.getALBUM_ID();
				} catch (Exception ex) {
				}
			}
		}

		if (songObject != null) {
			if (songObject.getFormNet())
				new listCommentService().execute(audioID);
			showView(songObject.getFormNet());
		}
		if (albumObject != null)
			new listCommentService().execute(audioID);
		return android;
	}

	void showView(boolean isOnline) {
		if (empty_loading != null) {
			if (isOnline) {
				layout_comment.setVisibility(View.VISIBLE);
				empty_loading.setVisibility(View.GONE);
			} else {
				layout_comment.setVisibility(View.GONE);
				empty_loading.setVisibility(View.VISIBLE);
				empty_progress.setVisibility(View.GONE);
				empty_error.setVisibility(View.VISIBLE);
				empty_noitem.setVisibility(View.GONE);
				empty_text.setVisibility(View.VISIBLE);
				empty_text.setText("Bình luận khi nghe nhạc Online!");
			}
		}
	}

	private void findviewByID(View view) {
		layout_comment = (RelativeLayout) view.findViewById(R.id.realativelayout_comment);
		listViewComnent = (ListView) view.findViewById(R.id.Comment_xListView);
		listViewComnent.setAdapter(adapter);
		listViewComnent.setOnScrollListener(this);
		progressBarFooter = (ProgressBarCircularIndeterminate) view.findViewById(R.id.progressBarloadmore);
		empty_loading = view.findViewById(R.id.empty_loading);
		empty_progress = (ProgressBar) empty_loading.findViewById(R.id.empty_loading_progress);
		empty_text = (TextView) empty_loading.findViewById(R.id.empty_loading_text);
		empty_error = (ImageView) empty_loading.findViewById(R.id.empty_loading_Error);
		empty_noitem = (ImageView) empty_loading.findViewById(R.id.empty_loading_NoItem);

		imgSend = (ImageView) view.findViewById(R.id.comment_imgSend);
		edtText = (EditText) view.findViewById(R.id.comment_edtext);
		
		
		listComment = new ArrayList<CommentObject>();
		adapter = new CommentAdapter(context, listComment);
		listViewComnent.setAdapter(adapter);
		imgSend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String user = PreferenceUtils.getString(context, TagName.KeyPreference_user);
				if (user != null) {
					String content = edtText.getText().toString();
					if (content != null && !content.equals(""))
						if (songObject != null && songObject.getFormNet()) {
							new sendCommentService().execute(content);
						} else
							new sendCommentService().execute(content);
					edtText.setText("");
				} else {
					alertDialog = new AlertDialog.Builder(context).setTitle("Bạn chưa đăng nhập!").setMessage("Hãy đăng nhập để comment!")
							.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									// if
									// (!type_SongAlbum.equals(TagName.Comment_typeVideo))
									// {
									// ((MainActivity)
									// context).switchContent(AccountLoginFragment.class.getName());
									// } else {
									// AccountLoginDialog accountLoginDialog =
									// new AccountLoginDialog();
									// accountLoginDialog.show(((VideoPlayActivity)
									// context).getSupportFragmentManager(),
									// null);
									// }
								}
							})
							// .setNegativeButton(android.R.string.no, new
							// DialogInterface.OnClickListener() {
							// public void onClick(DialogInterface dialog, int
							// which) {
							// // do nothing
							// }
							// })
							.setIcon(android.R.drawable.ic_dialog_alert).show();
				}
			}
		});

	}

	class sendCommentService extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... params) {
			String str = WServiceLib.sendCommnets(audioID, type_SongAlbum, "kenhnhac", params[0], PreferenceUtils.getString(context, TagName.KeyPreference_user));
			BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			new listCommentService().execute(audioID);
		}
	}

	class loginService extends AsyncTask<String, String, String> {
		ProgressDialog progressDialog = new ProgressDialog(getActivity());

		@Override
		protected String doInBackground(String... param) {
			String str = WServiceLib.login(param[0], param[1]);
			// BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (!progressDialog.isShowing())
				progressDialog.show();
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (progressDialog.isShowing())
				progressDialog.hide();
			if (result != null) {
				try {
					JsonReader.loginReader(result);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			if (HomeData.headerObject.getCODE().equals("0")) {
//				ImageLoader.getInstance().loadImage(HomeData.homeAccount.getAVATAR(), new SimpleImageLoadingListener() {
//					@Override
//					public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//						super.onLoadingComplete(imageUri, view, loadedImage);
//						PreferenceUtils.putString(context, TagName.KeyPreference_fullname, HomeData.homeAccount.getFULL_NAME());
//						PreferenceUtils.putString(context, TagName.KeyPreference_usercode, HomeData.homeAccount.getUSER_CODE());
//						PreferenceUtils.putString(context, TagName.KeyPreference_sex, HomeData.homeAccount.getSEX());
//						PreferenceUtils.putString(context, TagName.KeyPreference_birthday, HomeData.homeAccount.getBIRTH_DAY());
//						PreferenceUtils.putString(context, TagName.KeyPreference_user, HomeData.homeAccount.getUSER_NAME());
//						// PreferenceUtils.putString(context,
//						// TagName.KeyPreference_phone,HomeData.homeAccount.getMOBILE());
//						PreferenceUtils.putString(context, TagName.KeyPreference_avatar, BaseEngine.BitmapTobase64(loadedImage));
//						TagName.showToastShort(context, HomeData.headerObject.getMESSAGE());
//						alertDialog.dismiss();
//					}
//				});
				imageLoader.get(HomeData.homeAccount.getAVATAR(), new ImageLoader.ImageListener() {
			        @Override
			        public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
						PreferenceUtils.putString(context, TagName.KeyPreference_fullname, HomeData.homeAccount.getFULL_NAME());
						PreferenceUtils.putString(context, TagName.KeyPreference_usercode, HomeData.homeAccount.getUSER_CODE());
						PreferenceUtils.putString(context, TagName.KeyPreference_sex, HomeData.homeAccount.getSEX());
						PreferenceUtils.putString(context, TagName.KeyPreference_birthday, HomeData.homeAccount.getBIRTH_DAY());
						PreferenceUtils.putString(context, TagName.KeyPreference_user, HomeData.homeAccount.getUSER_NAME());
						// PreferenceUtils.putString(context,
						// TagName.KeyPreference_phone,HomeData.homeAccount.getMOBILE());
						PreferenceUtils.putString(context, TagName.KeyPreference_avatar, BaseEngine.BitmapTobase64(response.getBitmap()));
						TagName.showToastShort(context, HomeData.headerObject.getMESSAGE());
						alertDialog.dismiss();
			        }

					@Override
					public void onErrorResponse(VolleyError arg0) {
					}
			    });
			} else
				TagName.showToastShort(context, HomeData.headerObject.getMESSAGE());
		}
	}

	class listCommentService extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
//			if (m_PreviousTotalCount > 0)
//				((Activity)context).runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						progressBarFooter.setVisibility(View.VISIBLE);
//					}
//				});
			String str = WServiceLib.listCommnets(audioID, type_SongAlbum, page, pageSize);
			// BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null)
				try {
//					((Activity)context).runOnUiThread(new Runnable() {
//						@Override
//						public void run() {
//							progressBarFooter.setVisibility(View.GONE);
//						}
//					});
					listComment = JsonReader.listComment(result);
					try {
						if (listComment != null){
							adapter.setList(listComment);
						}else {
							empty_progress.setVisibility(View.GONE);
							empty_noitem.setVisibility(View.VISIBLE);
							txtStatus.setText("Chưa có bình luận nào!");
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (totalItemCount == 0 || adapter == null)
			return;
		if (m_PreviousTotalCount == totalItemCount) {
			return;
		}
		boolean loadMore = firstVisibleItem + visibleItemCount >= totalItemCount - 3;
		if (loadMore && firstVisibleItem > 0 && totalItemCount - m_PreviousTotalCount >= 10) {
			m_PreviousTotalCount = totalItemCount;
			xpage += 1;
			new listCommentService().execute(audioID);
		}

	}

}